package org.xxpay.pay.mq;

import com.alibaba.fastjson.JSONObject;
import org.apache.activemq.ScheduledMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.xxpay.core.common.util.MyLog;
import org.xxpay.pay.channel.alizftpay.AlizftpayApiService;
import org.xxpay.pay.service.CommonService;

import javax.jms.*;

@Component
public class Mq4AlizftpayTradeSettleConfirm {

    @Autowired
    private Queue alizftpaytradeSettleConfirmQueue;

    @Autowired
    private JmsTemplate jmsTemplate;

    @Autowired
    private CommonService commonService;

    @Autowired
    private AlizftpayApiService alizftpayApiService;


    private static final MyLog _log = MyLog.getLog(Mq4AlizftpayTradeSettleConfirm.class);

    public void send(String msg) {
        _log.info("发送MQ消息:msg={}", msg);
        this.jmsTemplate.convertAndSend(this.alizftpaytradeSettleConfirmQueue, msg);
    }

    /**
     * 发送延迟消息
     * @param msg
     * @param delay
     */
    public void send(String msg, long delay) {
        _log.info("发送MQ延时消息:msg={},delay={}", msg, delay);
        jmsTemplate.send(this.alizftpaytradeSettleConfirmQueue, new MessageCreator() {
            public Message createMessage(Session session) throws JMSException {
                TextMessage tm = session.createTextMessage(msg);
                tm.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_DELAY, delay);
                tm.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_PERIOD, 1*1000);
                tm.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_REPEAT, 1);
                return tm;
            }
        });
    }

    @JmsListener(destination = MqConfig.ALIZFTPAY_TRADE_SETTLE_CONFIRM_QUEUE_NAME)
    @Async("alizftpayTradeSettleConfirmMQExecutor")
    public void receive(String msg) {

        try {

            JSONObject obj = JSONObject.parseObject(msg);
            alizftpayApiService.tradeSettleConfirm(obj.getLong("alizftSettRecordId"));

        }catch (Exception e){
            _log.info("处理MQ异常！:msg={}",e, msg);
        }


    }
}
